<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace App\Model;

use Think\Model\RelationModel;
use Think\Page;

/**
 * 用户模型
 * Class UserModel
 * @package Home\Model
 */
class UserModel extends RelationModel {

    protected $tableName = 'accountant_users';

    public function __construct() {
        parent::__construct();
        $this->user_id = session('user_id');
    }

    /**
     * 登陆
     */
    public function login($username, $registration_id = '') {
        $result = array();
        if (!$username)
            $result = array('status' => -1, 'msg' => '请填写账号');
        if (!check_mobile($username))
            $result = array('status' => -1, 'msg' => '手机号格式不正确');

        $user = M('users')->where("mobile='{$username}'")->find();
        if (!$user) {
            $map['mobile_validated'] = 1;
            $map['mobile'] = $username;
            $map['nickname'] = 'xrk_' . rand(1, 9999);
            $map['reg_time'] = time();
            $user_id = M('users')->add($map);
            $encryptStr = array('user_id' => $user_id, 'time' => time());

            // 会员注册送优惠券
            $coupon = M('coupon')->where("send_end_time > " . time() . " and ((createnum - send_num) > 0 or createnum = 0) and type = 2")->select();
            foreach ($coupon as $key => $val) {
                // 送券            
                M('coupon_list')->add(array('cid' => $val['id'], 'type' => $val['type'], 'uid' => $user_id, 'send_time' => time()));
                M('Coupon')->where("id = {$val['id']}")->setInc('send_num'); // 优惠券领取数量加一            
            }
            if (!empty($registration_id)) {
                $result1 = M('user_registration')->where("user_id='{$user_id}'")->find();
                if (empty($result1)) {
                    M('user_registration')->add(array('user_id' => $user_id, 'is_login' => 1, 'registration_id' => $registration_id));
                } else {
                    M('user_registration')->where("user_id=$user_id ")->save(array('is_login' => 1));
                }
            }

            $res = $this->getCoupon($user_id, 0);
            $user['coupon_num'] = count($res['result']);
            $user['token'] = encrypt_token($encryptStr);
            return array('status' => 1, 'msg' => '注册成功', 'result' => $user);
        } elseif ($user['is_lock'] == 1) {
            $result = array('status' => -1, 'msg' => '账号异常已被锁定！！！');
        } else {
            $encryptStr = array('user_id' => $user['user_id'], 'time' => time());
            $user['token'] = encrypt_token($encryptStr);

            if (!empty($registration_id)) {
                $result1 = M('user_registration')->where("user_id='{$user['user_id']}'")->find();
                if (empty($result1)) {
                    M('user_registration')->add(array('user_id' => $user['user_id'], 'is_login' => 1, 'registration_id' => $registration_id));
                } else {
                    M('user_registration')->where("user_id={$user['user_id']} ")->save(array('is_login' => 1));
                }
            }
            $result = array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
        }
        return $result;
    }

    /**
     * 商家端登陆
     */
    public function appLogin($mobile, $password, $registration_id = '') {
        $result = array();
        if (!$mobile || !$password)
            $result = array('status' => -1, 'msg' => '请填写账号或密码', 'result' => []);
        if (!check_mobile($mobile))
            $result = array('status' => -1, 'msg' => '手机号格式不正确');
        $user = M('accountant_users')->where("mobile='{$mobile}' ")->find();
        if (!$user) {
            $result = array('status' => -1, 'msg' => '不存在账号!', 'result' => []);
        } elseif ($user['status'] != 1) {
            $result = array('status' => -1, 'msg' => '账号正在审核中!', 'result' => []);
        } elseif ($user['password'] != encrypt($password)) {
            return array('status' => -1, 'msg' => '密码错误！');
        } else {
            //加密token
            $encryptStr = array('user_id' => $user['au_id'], 'time' => time());
            $arr['token'] = encrypt_token($encryptStr);
            $arr['accountant_name'] = $user['username'];
            $arr['accountant_head'] = (strpos($user['head_pic'],'http') === false && $user['head_pic']) ? SITE_URL.$user['head_pic'] : $user['head_pic'];
            $arr['openid'] = $user['openid'];

            if($registration_id){
                M('accountant_users')->where('au_id = '.$user['au_id'])->save(
                    array('registered_id' => $registration_id)
                );
            }

            $result = array('status' => 1, 'msg' => '登陆成功', 'result' => $arr);
        }
        return $result;
    }

    /**
     * 第三方登录
     */
    public function thirdLogin($data = array()) {
        $openid = $data['openid']; //第三方返回唯一标识
        $unionid = $data['unionid']; //
        $oauth = $data['oauth']; //来源
        $registration_id = $data['registration_id']; //设备id
        if (empty($openid) && empty($oauth) && empty($unionid)) {
            return array('status' => -1, 'msg' => '参数有误', 'result' => array());
        }
        //获取用户信息
        if (!empty($unionid)) {
            $user = get_user_info($unionid, 4, $oauth);
        } else {
            $user = get_user_info($openid, 3, $oauth);
        }
        if (!$user) {
            //账户不存在 注册一个
            $map['password'] = '';
            $map['openid'] = $openid;
            $map['unionid'] = $unionid;
            $map['username'] = $data['nickname'];
            $map['reg_time'] = time();
            $map['oauth'] = $oauth;
            $map['head_pic'] = $data['head_pic'] ? $data['head_pic'] : '';
            $map['sex'] = $data['sex'];
            $map['reg_time'] = time();

            $row = M('users')->add($map);
            if (!empty($unionid)) {
                $user = get_user_info($unionid, 4, $oauth);
            } else {
                $user = get_user_info($openid, 3, $oauth);
            }
            //加密token
            $encryptStr = array('user_id' => $user['user_id'], 'time' => time());
            $user['token'] = encrypt_token($encryptStr);


        } else {
            //加密token
            $encryptStr = array('user_id' => $user['user_id'], 'time' => time());
            $user['token'] = encrypt_token($encryptStr);
        }

        M('users')->where("user_id = '{$user['user_id']}'")->save(array('token' => $user['token']));
        unset($user['password']);

        /*if (!empty($registration_id)) {
            $result = M('user_registration')->where("user_id='{$user['user_id']}'")->find();
            if (empty($result)) {
                M('user_registration')->add(array('user_id' => $user['user_id'], 'is_login' => 1, 'registration_id' => $registration_id));
            } else {
                M('user_registration')->where("user_id={$user['user_id']} ")->save(array('is_login' => 1));
            }
        }*/
        return array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
    }

    /**
     * 两个账号绑定
     */
    public function bindUser($user_id, $mobile) {
        $users = D('Users')->where("user_id={$user_id} or mobile={$mobile}")->order('reg_time asc')->select();
        $openid = '';
        $unionid = '';
        $head_pic = '';
        $nickname = '';
        $oauth = '';
        foreach ($users as $key => $value) {
            if (!empty($value['opendid'])) {
                $openid = $value['opendid'];
            }
            if (!empty($value['unionid'])) {
                $unionid = $value['unionid'];
            }
            if (!empty($value['head_pic'])) {
                $head_pic = $value['head_pic'];
            }
            if (!empty($value['nickname'])) {
                $nickname = $value['nickname'];
            }
            if (!empty($value['oauth'])) {
                $oauth = $value['oauth'];
            }
        }
        if (count($users) > 1) {
            $data['mobile'] = $mobile;
            $data['openid'] = $openid;
            $data['unionid'] = $unionid;
            $data['head_pic'] = $head_pic;
            $data['nickname'] = $nickname;
            $data['oauth'] = $oauth;
            $data['mobile_validated'] = 1;
            $rs = D('Users')->where("user_id={$users[0]['user_id']} ")->save($data);
            D('Users')->where("user_id={$users[1]['user_id']} ")->delete();
            $user_info = D('Users')->where(array('mobile' => $mobile))->find();
        } else {
            $rs = D('Users')->where("user_id={$user_id} ")->save(array('mobile' => $mobile, 'mobile_validated' => 1));
            $user_info = D('Users')->where("user_id={$user_id} ")->find();
        }
        //加密token
        $encryptStr = array('user_id' => $user_id, 'time' => time());
        $user_info['token'] = encrypt_token($encryptStr);
        return $user_info;
    }

    /**
     * 店铺收藏
     * @param type $user_id 用户id
     * @param type $shop_id 店铺id
     * @return type
     */
    public function collectShop($user_id, $shop_id) {
        $count = M('user_collect')->where("user_id = $user_id and shop_id = $shop_id")->count();
        if ($count > 0)
            return array('status' => -1, 'msg' => '店铺已收藏');
        M('user_collect')->add(array('shop_id' => $shop_id, 'user_id' => $user_id, 'add_time' => time()));
        return array('status' => 1, 'msg' => '收藏成功!');
    }

    /**
     * 获取商品收藏列表
     * @param $user_id  用户id
     */
    public function getCollect($user_id) {
        $count = M('user_collect')->where(array('user_id' => $user_id))->count();
        $sql = "SELECT c.collect_id,c.add_time,s.shop_id,s.shop_name,s.shop_logo,s.shop_type FROM __PREFIX__user_collect c " .
                "inner JOIN __PREFIX__seller_shop s ON s.shop_id = c.shop_id " .
                "WHERE c.user_id = " . $user_id .
                " ORDER BY c.add_time DESC ";
        $result = M()->query($sql);
        return $result;
    }

    /**
     * 申请洗车手
     * @param $param 参数
     * @return array
     */
    public function applySeller($param) {
        if (!check_mobile($param['mobile'])) {
            return array('status' => -1, 'msg' => '手机号格式不正确');
        }
        if (!$param['code']) {
            jsonReturn(-1, '验证码不能为空');
        }
        $res = $this->checkSmsCode($param['mobile'], $param['code']);
        if (empty($res['status'])) {
            jsonReturn($res['status'], $res['msg']);
        }
        if (empty($param['password']) || empty($param['seller_name'])) {
            return array('status' => -1, 'msg' => '请输入用户名或密码');
        }
        $user = M('seller')->where(array('mobile' => $param['mobile']))->find();
        if (!empty($user)) {
            return array('status' => -1, 'msg' => '账号已存在');
        }

        $data['mobile'] = $param['mobile'];
        $data['seller_name'] = $param['seller_name'];
        $data['sex'] = empty($param['sex']) ? 1 : 2;
        $data['birthday'] = $param['birthday'];
        $data['front_img'] = $param['front_img'];
        $data['back_img'] = $param['back_img'];
        $data['seller_pic'] = $param['seller_pic'];
        $data['password'] = encrypt($param['password']);
        $data['add_time'] = time();
        $sellerMod = D('seller');
        $seller_id = $sellerMod->add($data);

        if ($seller_id > 0) {
//                $pay_points = xrkCache('basic.reg_integral'); // 会员注册赠送积分
//                if ($pay_points > 0) {
//                    sellerLog($seller_id, 0, $pay_points, '会员注册赠送积分'); // 记录日志流水
//                }
            // 会员注册送优惠券
            $coupon = M('coupon')->where("send_end_time > " . time() . " and ((createnum - send_num) > 0 or createnum = 0) and type = 2")->select();
            if (!empty($coupon)) {
                foreach ($coupon as $key => $val) {
                    M('coupon_list')->add(array('cid' => $val['id'], 'type' => $val['type'], 'uid' => $seller_id, 'send_time' => time()));
                    M('Coupon')->where("id = {$val['id']}")->setInc('send_num'); // 优惠券领取数量加一
                }
            }
            return array('status' => 1, 'msg' => '申请成功，审核中', 'result' => array());
        } else {
            return array('status' => -1, 'msg' => '申请失败');
        }
    }

    public function getBonusList($page = 1,$limit = 6,$cac_count = false) {
        $select = M('pay_log')
            ->field('id,type,money,rate,add_time')
            ->where('au_id = '.$this->user_id.' and status = 1 and type > 0');

        if($cac_count){
            return $select->count();
        }
        $select = $select->page($page,$limit)->order('add_time desc')->select();
        if($select){
            $type = C('ACCOUNTING_LOG_TYPE');
            foreach ($select as &$find) {
                $money = number_format(abs(($find['money'] * $find['rate'] / 100)),2);
                $find['money'] = $find['money'] >= 0 ? '+￥'.$money : '-￥'.$money;
                $find['type_desc'] = $type[$find['type']];
                $find['time'] = date('Y-m-d H:i', $find['add_time']);

            }
        }else{
            return false;
        }
        return $select;
    }

    public  function getBonusDetail($id = 0){
        $id = $id ? $id : 0;
        $find = M('pay_log')->alias('pl')
            ->join('left join __QUESTION__ as q on pl.question_id = q.id')
            ->field('pl.*,q.title')
            ->where('pl.id =  '.$id)
            ->find();
        if($find){
            $find['money'] = number_format($find['money'] * $find['rate'] / 100,2);
        }
        return $find;
    }



    public function getQuestionDetail($user_id) {
        $user_id = $user_id ? $user_id : 0;

        $select = M('answer')->alias('a')
            ->join('left join __QUESTION__ as q on a.question_id = q.id')
            ->field('q.cat_ids')
            ->where('a.accountant_id = '.$user_id)
            ->select();

        $cats = D('category')->getKVList();
        $arr = array();
        $total = 0;
        foreach ($cats as $key =>$val) {
            $num = 0;
            foreach ($select as $item) {
                if(in_array($key,explode(',',$item['cat_ids']))){
                    $num += 1;
                }
            }
            $total += $num;
            $arr[] = array('name' => $val , 'num' => $num);
        }

        return array('data' => $arr, 'total' => $total);

    }


    /**
     * 注册
     * @param $username  手机
     * @param $password  密码
     * @param $password2 确认密码
     * @return array
     */
    public function reg($post) {
        $username = $post['phone'];
        $code = $post['identifying_code'];
        $password = trim($post['new_password']);
        $password2 = trim($post['confirm_password']);
        $registered_id = trim($post['registered_id']);
        $professionalList = trim($post['professionalList']);
        $is_validated = 0;

        if (check_mobile($username)) {
            $is_validated = 1;
            $map['mobile_validated'] = 1;
            $map['mobile'] = $username; //手机注册
            $map['username'] = $post['accountant_name'];

            $map['head_pic'] = '';
        }

        if ($is_validated != 1)
            return array('status' => -1, 'msg' => '请用手机号注册');

        $exited = M('accountant_users')->where(" mobile = '$username' and status = 1 ")->count();
        if ($exited)
            return array('status' => -1, 'msg' => '手机号已存在');

        $check = $this->checkSmsCode($username,$code);
        if ($check['status'] != 1)
            return array('status' => -1, 'msg' => $check['msg']);

        //验证两次密码是否匹配
        if ($password2 != $password)
            return array('status' => -1, 'msg' => '两次输入密码不一致');
        if(strlen($password) < 6 || strlen($password) > 12){
            return array('status' => -1, 'msg' => '密码长度须在6-12位字母数字之间');
        }

        //验证是否存在用户名
        if (get_user_info($username, 2))
            return array('status' => -1, 'msg' => '账号已存在');

        if(!$map['username']){
            return array('status' => -1, 'msg' => '请输入姓名');
        }

        $region = explode(',',$post['region']);
        if (count($region) != 2)
            return array('status' => -1, 'msg' => '请选择对应的省份城市');

        if (!$professionalList)
            return array('status' => -1, 'msg' => '请选择专业类型');

        if (!$post['accountant_code'])
            return array('status' => -1, 'msg' => '请填写会计师职业证码');

        $accountant_code = M('accountant_users')->where("professional_num = '$post[accountant_code]' ")->count();
        if ($accountant_code > 0)
            return array('status' => -1, 'msg' => '会计师职业证码已存在');

        /*$post['job_img'] = $this->uploadImg('job_img');
        if (!$post['job_img'])
            return array('status' => -1, 'msg' => '请上传会计师职业证图片');
        */

        $map['password'] = encrypt($password);
        $map['professional_num'] = $post['accountant_code'];
        //$map['professional_pic'] = $post['job_img'];
        $map['professional_pic'] = '';
        $map['province'] = (int)$region[0];
        $map['city'] = (int)$region[1];
        $map['oauth'] = 'app';
        $map['status'] = 0;
        $map['registered_id'] = $registered_id;
        $map['cat_ids'] = $professionalList;
        $map['reg_time'] = time();
        $test_month = getTestMonth();
        $time = strtotime(date('Y-m-d 23:59:59'));
        $map['expired_time'] = strtotime("+".$test_month." months", $time);

        $user_id = M('accountant_users')->add($map);
        if (!$user_id)
            return array('status' => -1, 'msg' => '注册失败');

        //$user = M('accountant_users')->where("au_id = {$user_id}")->find();

        //加密token
        //$encryptStr = array('user_id' => $user['au_id'], 'time' => time());
        //$user['token'] = encrypt_token($encryptStr);
        return array('status' => 1, 'msg' => '注册成功', 'result' => '');
    }


    /**
     * 极光推送
     */
    function jpush($question_id,$reg_id,$txt,$type=1){
        $bool = false;
        Vendor("JPush.JPush");
        $client = new \JPush(xrkCache('jpush.jpush_appkey'),xrkCache('jpush.jpush_master_secret'));
        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($reg_id)
            ->addIosNotification($txt,'default', '+1', true, '',array('id' => $question_id))
            ->send();

        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($reg_id)
            ->addAndroidNotification($txt, '会计问答', 1, array('id' => $question_id))
            ->addIosNotification($txt,'default', '+1', true, '',array('id' => $question_id))
            ->sends();

        $add = array(
            'reg_id' =>$reg_id,
            'content' =>$txt,
            'question_id' =>$question_id,
            'type' =>$type,
            'add_time' =>time(),
        );
        if($result->data->sendno){
            $add['status'] = 1;
            M('jpush_log')->add($add);
            $bool = true;
        }else{
            $add['status'] = 0;
            M('jpush_log')->add($add);
            $bool = false;
        }
        return $bool;
    }


    /**
     * 获取当前登录用户信息
     */
    public function getInfo($user_id) {
        if (!$user_id > 0)
            return array('status' => -1, 'msg' => '缺少参数', 'result' => '');
        $user_info = M('accountant_users')->where("au_id = $user_id and status = 1 ")->find();

        if (!$user_info)
            return array('status' => -1, 'msg' => '用户不存在', 'result' => '');

        $arr['au_id'] = $user_info['au_id'];
        $arr['accountant_code'] = $user_info['professional_num'];
        $arr['accountant_head'] = (strpos($user_info['head_pic'],'http') === false && $user_info['head_pic']) ? SITE_URL.$user_info['head_pic'] : $user_info['head_pic'];
        $arr['accountant_name'] = $user_info['username'];
        $arr['accountant_unit'] = $user_info['work_unit'];
        $arr['phone'] = $user_info['mobile'];
        $arr['professionalList'] = getCatArr($user_info['cat_ids']);
        $arr['region'] = $user_info['province'].','.$user_info['city'];
        $arr['reward_money'] = $user_info['reward_money'];
        $arr['sex'] = $user_info['sex'];
        $arr['bonus_money'] = $user_info['bonus_money'];
        $arr['charge_money'] = $user_info['charge_money'];
        $arr['outcash_money'] = $user_info['outcash_money'];
        $arr['adoption_num'] = $user_info['adoption_num'];
        $arr['is_expried'] = ($user_info['expired_time'] < time()) ? true : false;
        $arr['expired_time'] = $user_info['expired_time'] ? date('Y-m-d',$user_info['expired_time']) : 0;
        $arr['year_fee'] = getYearMoney();
        $arr['is_prompt'] = false;
        $time = getPromptDay() * 86400;
        if($arr['is_expried'] && ($user_info['expired_time'] + $time > time())){
            $arr['is_prompt'] = true;
        }
        return array('status' => 1, 'msg' => '获取成功', 'result' => $arr);
    }

    public function getAreaList(){
        //  获取省份
        $data = array();
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->field('id,name')->select();
        foreach($province as $p){
            $city = M('region')->where(array('parent_id' => $p['id'], 'level' => 2))->field('id,name')->select();
            $temp = $p;
            foreach($city as $c){
                $temp['child'][] = $c;
            }
            $data[] = $temp;
        }
        return $data;
    }

    /**
     * 更新用户信息
     * @param $user_id
     * @param $post  要更新的信息
     * @return bool
     */
    public function updateInfo($user_id,$data) {
        if (!$user_id > 0)
            return array('status' => -1, 'msg' => '缺少参数', 'result' => '');

        $arr = array();
        $data['accountant_head'] = $this->uploadImg('accountant_head');

        if($data['accountant_code']) {
            $accountant_code = M('accountant_users')->where("professional_num = '$data[accountant_code]' ")->count();
            if ($accountant_code > 0) {
                return array('status' => -1, 'msg' => '会计师职业证码已存在');
            }
            $arr['professional_num'] = $data['accountant_code'];
        }
        if($data['accountant_head']) {
            $arr['head_pic'] = $data['accountant_head'];
        }
        if($data['accountant_name'])
            $arr['username'] = $data['accountant_name'];
        if($data['accountant_unit'])
            $arr['work_unit'] = $data['accountant_unit'];
        if($data['phone']) {
            $check = $this->checkSmsCode($data['phone'],$data['identifying_code']);
            if($check['status'] != 1){
                return array('status' => -1, 'msg' => $check['msg'], 'result' => '');
            }

            $exited = M('accountant_users')->where(" mobile = '".$data['phone']."' and status = 1 ")->count();
            if ($exited) {
                return array('status' => -1, 'msg' => '手机号已存在');
            }

            $arr['mobile'] = $data['phone'];
            $arr['mobile_validated'] = 1;
        }

        if($data['professionalList'] === '0'){
            $arr['cat_ids'] = '';
        }elseif($data['professionalList']) {
            $arr['cat_ids'] = $data['professionalList'];
        }

        if($data['region']) {
            $ex = explode(',',$data['region']);
            $arr['province'] = (int)$ex[0];
            $arr['city'] = (int)$ex[1];
        }
        if(is_numeric($data['sex']) !== false)
            $arr['sex'] = $data['sex'];

        if($data['wechat'])
            $arr['openid'] = $data['wechat'];


        $bool = M('accountant_users')->where("au_id = {$user_id}")->data($arr)->save();

        if($bool)
            return array('status' => 1, 'msg' => '更新成功', 'result' => '');
        else
            return array('status' => -1, 'msg' => '更新失败或未作任何修改', 'result' => '');
    }

    public function updatePassword($user_id,$data) {
        if (!$user_id > 0)
            return array('status' => -1, 'msg' => '缺少参数', 'result' => '');

        $find = M('accountant_users')->where('au_id = '.$user_id . " and mobile = '$data[phone]' ")->find();

        if (!$find)
            return array('status' => -1, 'msg' => '手机号不正确', 'result' => '');

        $find = M('accountant_users')->where('au_id = '.$user_id . " and mobile = '$data[phone]' and password = '".encrypt($data['old_password'])."' ")->find();

        if (!$find)
            return array('status' => -1, 'msg' => '旧密码不正确', 'result' => '');

        if($find['status'] != 1){
            return array('status' => -1, 'msg' => '会计师账户未审核通过！', 'result' => '');
        }

        if (($data['new_password'] != $data['confirm_password']))
            return array('status' => -1, 'msg' => '新密码填写不一致', 'result' => '');

        if($find['password'] == encrypt($data['new_password'])){
            return array('status' => -1, 'msg' => '不能与旧密码相同！', 'result' => '');
        }

        if(mb_strlen($data['new_password'],'utf-8') < 6 ||
            mb_strlen($data['new_password'],'utf-8') > 20){
            return array('status' => -1, 'msg' => '请输入6-20位以内的字符密码', 'result' => '');
        }

        $bool = M('accountant_users')->where("au_id = {$user_id}")->data(array(
            'password' => encrypt($data['new_password'])
        ))->save();
        if($bool)
            return array('status' => 1, 'msg' => '修改成功', 'result' => '');
        else
            return array('status' => -1, 'msg' => '修改失败', 'result' => '');
    }


    public function retrievePassword($data) {
        $find = M('accountant_users')->where("mobile = '$data[phone]'  ")->find();
        if (!$find)
            return array('status' => -1, 'msg' => '查询不到会计师信息，请检查手机号', 'result' => '');

        $check = $this->checkSmsCode($data['phone'],$data['identifying_code']);
        if($check['status'] != 1){
            return array('status' => -1, 'msg' => $check['msg'], 'result' => '');
        }

        if (($data['new_password'] != $data['confirm_password']))
            return array('status' => -1, 'msg' => '新密码填写不一致', 'result' => '');


        if($find['status'] != 1){
            return array('status' => -1, 'msg' => '会计师账户未审核通过！', 'result' => '');
        }

        if($find['password'] == encrypt($data['new_password'])){
            return array('status' => -1, 'msg' => '不能与旧密码相同！', 'result' => '');
        }

        if(mb_strlen($data['new_password'],'utf-8') < 6 ||
            mb_strlen($data['new_password'],'utf-8') > 20){
            return array('status' => -1, 'msg' => '请输入6-20位以内的字符密码', 'result' => '');
        }

        $bool = M('accountant_users')->where("mobile = '$data[phone]' ")->data(array(
            'password' => encrypt($data['new_password'])
        ))->save();
        if($bool)
            return array('status' => 1, 'msg' => '重置成功', 'result' => '');
        else
            return array('status' => -1, 'msg' => '重置失败', 'result' => '');
    }

    /**
     * 获取最近一笔订单
     */
    public function getLastOrder($user_id) {
        $last_order = M('order')->where("user_id = {$user_id}")->order('order_id DESC')->find();
        return $last_order;
    }

    /**
     * 获取订单商品
     */
    public function getOrderGoods($order_id) {
        $sql = "SELECT og.*,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE order_id = " . $order_id;
        $goodsList = $this->query($sql);

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $goodsList;
        return $return;
    }

    /**
     * 获取账户资金记录
     */
    public function getUserLog($user_id, $type = 0) {
        //查询条件
//        $type = I('get.type',0);
        if ($type == 1) {
            //收入
            $where = 'user_money > 0 OR pay_points > 0 AND user_id=' . $user_id;
        }
        if ($type == 2) {
            //支出
            $where = 'user_money < 0 OR pay_points < 0 AND user_id=' . $user_id;
        }

        $count = M('user_log')->where($where ? $where : 'user_id = ' . $user_id)->count();
        $Page = new Page($count, 16);
        $logs = M('user_log')->where($where ? $where : 'user_id = ' . $user_id)->order('change_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $logs;
        $return['show'] = $Page->show();

        return $return;
    }

    /**
     * 获取优惠券
     */
    public function getCoupon($user_id, $type = 0) {
        //    $type = I('get.type',0);           
        $where = ' AND l.order_id = 0 AND c.use_end_time > ' . time(); // 未使用
        //已使用
        if ($type == 1) {
            $where = ' AND l.order_id > 0 AND l.use_time > 0 ';
        }
        //已过期
        if ($type == 2) {
            $where = ' AND ' . time() . ' > c.use_end_time ';
        }
        //获取数量
        $sql = "SELECT count(l.id) as total_num FROM __PREFIX__coupon_list" .
                " l LEFT JOIN __PREFIX__coupon" .
                " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}";
        $count = $this->query($sql);
        $count = $count[0]['total_num'];

        $Page = new Page($count, 10);

        $sql = "SELECT l.*,c.name,c.money,c.use_end_time,c.use_start_time,c.condition FROM __PREFIX__coupon_list" .
                " l LEFT JOIN __PREFIX__coupon" .
                " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}  ORDER BY l.send_time DESC,l.use_time LIMIT {$Page->firstRow},{$Page->listRows}";

        $rs = $this->query($sql);
        foreach ($rs as $key => $value) {
            $rs[$key]['use_start_time'] = date('Y.m.d', $value['use_start_time']);
            $rs[$key]['use_end_time'] = date('Y.m.d', $value['use_end_time']);
            $rs[$key]['money'] = floatval($value['money']);
            $rs[$key]['condition'] = floatval($value['condition']);
        }

        $return['status'] = 1;
        $return['msg'] = '获取成功';
        $return['result'] = $rs;
        return $return;
    }

    /**
     * 获取车辆列表
     */
    public function getCar($user_id = 0, $is_default = 0) {
        if ($is_default > 0) {
            $carList = M('user_car')->where(array('user_id' => $user_id, 'is_default' => 1))->select();
        } else {
            $carList = M('user_car')->where(array('user_id' => $user_id))->select();
        }
        if (count($carList) > 0) {
            $return['status'] = 1;
            $return['msg'] = '获取成功';
            $return['result'] = $carList;
        } else {
            $return['status'] = 1;
            $return['msg'] = '无数据';
            $return['result'] = [];
        }
        return $return;
    }

    public function uploadImg($name)
    {
        if ($_FILES[$name]['name']) {
            $upload = new \Think\Upload(); // 实例化上传类
            $upload->maxSize = $map['author'] = (1024 * 1024 * 3); // 设置附件上传大小 管理员10M  否则 3M
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
            $upload->rootPath = './Public/upload/head_pic/'; // 设置附件上传根目录
            $upload->replace = true; // 存在同名文件是否是覆盖，默认为false
            //$upload->saveName  =  'file_'.$id; // 存在同名文件是否是覆盖，默认为false
            // 上传文件
            $upinfo = $upload->upload();
            if (!$upinfo) {// 上传错误提示错误信息
                return $this->error($upload->getError());
            } else {
                foreach ($upinfo as $key => $val) {
                    $comment_img = '/Public/upload/head_pic/' . $val['savepath'] . $val['savename'];
                }
//                    $result['data'] = getThumbImg($avatar, 100, 100);
                return $comment_img;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取评论列表
     * @param $user_id 用户id
     * @param $status  状态 0 未评论 1 已评论
     * @return mixed
     */
    public function getComment($user_id, $status = 2) {
        if ($status == 1) {
            //已评论
            $count2 = M('')->query("select count(*) as count from `__PREFIX__comment`  as c inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id");
            $count2 = $count2[0]['count'];

            $page = new Page($count2, 10);
            $selectSql = "c.comment_id,c.goods_id,c.email,c.username,c.content,c.deliver_rank,";
            $selectSql .= "c.ip_address,c.is_show,c.parent_id,c.user_id,c.img,c.order_id,c.goods_rank,c.service_rank,c.is_show_name";
            $sql = "select c.*,g.*,(select order_sn from  __PREFIX__order where order_id = c.order_id ) as order_sn  from  __PREFIX__comment as c inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id order by c.add_time desc LIMIT {$page->firstRow},{$page->listRows}";
        } else {
            $countsql = " select count(1) as comment_count from __PREFIX__order_goods as og
        	left join __PREFIX__order as o on o.order_id = og.order_id where o.user_id = $user_id  and og.is_send = 1 and (o.order_status = 2 or o.order_status = 4)";
            $where = '';
            if ($status == 0) {
                $countsql .= $where = " and og.is_comment = 0";
            }
            $comment = M()->query($countsql);
            $count1 = $comment[0][comment_count]; // 待评价
            $page = new Page($count1, 3);
            $sql = " select og.*,o.*,c.add_time AS c_time from __PREFIX__order_goods as og 
            left join __PREFIX__order as o on o.order_id = og.order_id LEFT JOIN __PREFIX__comment AS c ON og.goods_id = c.goods_id AND c.order_id = o.order_id where o.user_id = $user_id and og.is_send = 1 
            and (o.order_status = 2 or o.order_status = 4)
            $where order by o.order_id desc  LIMIT {$page->firstRow},{$page->listRows}";
        }

        $show = $page->show();
        $comment_list = M()->query($sql);
        if ($status != 1) {
            foreach ($comment_list as $item => $value) {
                $comment_list[$item]['add_time'] = $comment_list[$item]['c_time'];
            }
        }
        if ($comment_list) {
            $return['result'] = $comment_list;
            $return['show'] = $show; //分页
            return $return;
        } else {
            return array();
        }
    }

    /**
     * 添加评论
     * @param $order_id  订单id
     * @param $goods_id  商品id
     * @param $user_email用户邮箱地址
     * @param $username  用户名
     * @return bool
     */
    public function addComment($add) {
        if (!$add[order_id] || !$add[goods_id])
            return array('status' => -1, 'msg' => '非法操作', 'result' => '');

        //检查订单是否已完成
        $order = M('order')->where("order_id = {$add['order_id']} AND user_id = {$add['user_id']}")->find();
        if ($order['order_status'] != 2)
            return array('status' => -2, 'msg' => '该笔订单还未确认收货', 'result' => '');

        //检查是否已评论过
        $goods = M('comment')->where("order_id = {$add['order_id']} AND goods_id = {$add['goods_id']}")->find();
        if ($goods)
            return array('status' => -3, 'msg' => '您已经评论过该商品', 'result' => '');

        $row = M('comment')->add($add);
        if ($row) {
            //更新订单商品表状态
            M('order_goods')->where(array('goods_id' => $add['goods_id'], 'order_id' => $add['order_id']))->save(array('is_comment' => 1));
            M('goods')->where(array('goods_id' => $add['goods_id']))->setInc('comment_count', 1); // 评论数加一  
            // 查看这个订单是否全部已经评论,如果全部评论了 修改整个订单评论状态            
            $comment_count = M('order_goods')->where("order_id ='{$add['order_id']}' and is_comment = 0")->count();
            if ($comment_count == 0) { // 如果所有的商品都已经评价了 订单状态改成已评价
                M('order')->where("order_id ={$add['order_id']}")->save(array('order_status' => 4));
                finish_bonus_log($order, 3); //完成订单时，进行分成
                order_give($order); //自动完成 送积分送券
            }
            return array('status' => 1, 'msg' => '评论成功', 'result' => '');
        }
        return array('status' => -4, 'msg' => '评论失败', 'result' => '');
    }

    /**
     * 邮箱或手机绑定
     * @param $email_mobile  邮箱或者手机
     * @param int $type  1 为更新邮箱模式  2 手机
     * @param int $user_id  用户id
     * @return bool
     */
    public function updateEmailMobile($email_mobile, $user_id, $type = 1) {
        //检查是否存在邮件
        if ($type == 1)
            $field = 'email';
        if ($type == 2)
            $field = 'mobile';
        $condition['user_id'] = array('neq', $user_id);
        $condition[$field] = $email_mobile;

        $is_exist = M('users')->where($condition)->find();
        if ($is_exist)
            return false;
        unset($condition[$field]);
        $condition['user_id'] = $user_id;
        $validate = $field . '_validated';
        M('users')->where($condition)->save(array($field => $email_mobile, $validate => 1));
        return true;
    }




    /**
     * 地址添加/编辑
     * @param $user_id 用户id
     * @param $user_id 地址id(编辑时需传入)
     * @return array
     */
    public function addAddress($user_id, $address_id = 0, $data) {
        $post = $data;
        if ($address_id == 0) {
            $c = M('UserAddr')->where("user_id = $user_id")->count();
            if ($c >= 20)
                return array('status' => -1, 'msg' => '最多只能添加20个收货地址', 'result' => '');
        }

        //检查手机格式
        if ($post['consignee'] == '')
            return array('status' => -1, 'msg' => '收货人不能为空', 'result' => '');
        if (!$post['province']) {
            if ($post['province'] < 47493 && (!$post['city'] || !$post['district'])) {
                return array('status' => -1, 'msg' => '所在地区不能为空', 'result' => '');
            }
        }

        if (!$post['address'])
            return array('status' => -1, 'msg' => '地址不能为空', 'result' => '');
        if (!check_mobile($post['mobile']))
            return array('status' => -1, 'msg' => '手机号码格式有误', 'result' => '');

        //编辑模式
        if ($address_id > 0) {

            $address = M('user_addr')->where(array('address_id' => $address_id, 'user_id' => $user_id))->find();
            if ($post['is_default'] == 1 && $address['is_default'] != 1)
                M('user_addr')->where(array('user_id' => $user_id))->save(array('is_default' => 0));
            $row = M('user_addr')->where(array('address_id' => $address_id, 'user_id' => $user_id))->save($post);
            if (!$row)
                return array('status' => 1, 'msg' => '无修改', 'result' => array());
            return array('status' => 1, 'msg' => '编辑成功', 'result' => array());
        }
        //添加模式
        $post['user_id'] = $user_id;

        // 如果目前只有一个收货地址则改为默认收货地址
        $c = M('user_addr')->where("user_id = {$post['user_id']}")->count();
        if ($c == 0)
            $post['is_default'] = 1;

        $address_id = M('user_addr')->add($post);
        //如果设为默认地址
        $insert_id = M()->getLastInsID();
        $map['user_id'] = $user_id;
        $map['address_id'] = array('neq', $insert_id);

        if ($post['is_default'] == 1)
            M('user_addr')->where($map)->save(array('is_default' => 0));
        if (!$address_id)
            return array('status' => -1, 'msg' => '添加失败', 'result' => '');


        return array('status' => 1, 'msg' => '添加成功', 'result' => $address_id);
    }

    /**
     * 设置默认收货地址
     * @param $user_id
     * @param $address_id
     */
    public function setDefault($user_id, $address_id) {
        M('user_addr')->where(array('user_id' => $user_id))->save(array('is_default' => 0)); //改变以前的默认地址地址状态
        $row = M('user_addr')->where(array('user_id' => $user_id, 'address_id' => $address_id))->save(array('is_default' => 1));
        if (!$row)
            return false;
        return true;
    }

    /**
     * 修改密码
     * @param $user_id  用户id
     * @param $old_password  旧密码
     * @param $new_password  新密码
     * @param $confirm_password 确认新 密码
     */
    public function password($user_id, $old_password, $new_password, $confirm_password, $is_update = true) {
        $data = $this->getInfo($user_id);
        $user = $data['result'];
        if (strlen($new_password) < 6)
            return array('status' => -1, 'msg' => '密码不能低于6位字符', 'result' => '');
        if ($new_password != $confirm_password)
            return array('status' => -1, 'msg' => '两次密码输入不一致', 'result' => '');
        //验证原密码
        if ($is_update && ($user['password'] != '' && encrypt($old_password) != $user['password']))
            return array('status' => -1, 'msg' => '密码验证失败', 'result' => '');
        $row = M('users')->where("user_id='{$user_id}'")->save(array('password' => encrypt($new_password)));
        if (!$row)
            return array('status' => -1, 'msg' => '修改失败', 'result' => '');
        return array('status' => 1, 'msg' => '修改成功', 'result' => '');
    }

    /**
     * 取消订单
     */
    public function cancelOrder($user_id, $order_id) {
        $order = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        //检查是否未支付订单 已支付联系客服处理退款
        if (empty($order))
            return array('status' => -1, 'msg' => '订单不存在', 'result' => '');
        //检查是否未支付的订单
        if ($order['pay_status'] > 0 || $order['order_status'] > 0)
            return array('status' => -1, 'msg' => '支付状态或订单状态不允许', 'result' => '');
        //获取记录表信息
        //$log = M('user_log')->where(array('order_id'=>$order_id))->find();
        //有余额支付的情况
        if ($order['user_money'] > 0 || $order['integral'] > 0) {
            userLog($user_id, $order['user_money'], $order['integral'], "订单取消，退回{$order['user_money']}元,{$order['integral']}积分");
        }

        $row = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->save(array('order_status' => 3));

        $data['order_id'] = $order_id;
        $data['action_user'] = $user_id;
        $data['action_note'] = '您取消了订单';
        $data['order_status'] = 3;
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = '用户取消订单';
        M('order_remark')->add($data); //订单操作记录		

        if (!$row)
            return array('status' => -1, 'msg' => '操作失败', 'result' => '');
        return array('status' => 1, 'msg' => '操作成功', 'result' => '');
    }

    /**
     * app发送短信验证码记录
     * @param $mobile
     * @param $code
     * @param $session_id
     */
    public function sms($mobile, $code, $session_id) {
        //判断是否存在验证码
        $data = M('sms')->where(array('mobile' => $mobile, 'session_id' => $session_id))->order('id DESC')->find();
        //获取时间配置
        $sms_time_out = xrkCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //120秒以内不可重复发送
        if ($data && (time() - $data['add_time']) < $sms_time_out)
            return array('status' => -1, 'msg' => $sms_time_out . '秒内不允许重复发送');
        $row = M('sms')->add(array('mobile' => $mobile, 'status' => $code, 'add_time' => time(), 'session_id' => $session_id));
        if (!$row)
            return array('status' => -1, 'msg' => '发送失败');
        //$send = sendSMS($mobile,'您好，你的验证码是：'.$code);
        $send = sendSMS($mobile, $code);
        if (!$send)
            return array('status' => -1, 'msg' => '发送失败');
        return array('status' => 1, 'msg' => '发送成功');
    }

    /**
     * 短信验证码验证
     * @param $mobile   手机
     * @param $code  验证码
     * @return bool
     */
    public function smsCodeVerify($mobile, $code, $session_id) {
        //判断是否存在验证码
        $data = M('sms')->where(array('mobile' => $mobile, 'session_id' => $session_id, 'status' => $code))->order('id DESC')->find();
        if (empty($data))
            return array('status' => -1, 'msg' => '手机验证码不匹配');

        //获取时间配置
        $sms_time_out = xrkCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //验证是否过时
        if ((time() - $data['add_time']) > $sms_time_out)
            return array('status' => -1, 'msg' => '手机验证码超时'); //超时处理
        M('sms')->where(array('mobile' => $mobile, 'session_id' => $session_id, 'status' => $code))->delete();
        return array('status' => 1, 'msg' => '验证成功');
    }

    /**
     * app发送短信验证码记录
     * @param $mobile
     */
    public function sendSmsCode($mobile) {

        if (!check_mobile($mobile)) {
            return array('status' => -1, 'msg' => '手机号码格式有误');
        }

        $data = M('sms')->where(array('mobile' => $mobile))->order('id DESC')->find();
        $sms_time_out = xrkCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        /*if ($data && (time() - $data['add_time']) < $sms_time_out) {
            return array('status' => -1, 'msg' => $sms_time_out . '秒内不允许重复发送');
        }*/

        $code = mt_rand(100000, 999999);
        $send = sendSMS($mobile, $code);
        if ($send) {
            $sms_data['code'] = $code;
            $sms_data['mobile'] = $mobile;
            $sms_data['add_time'] = time();
            $sms_data['session_id'] = session_id();
            M('sms')->add($sms_data);
            $res = array('status' => 1, 'msg' => '验证码已发送，请注意查收');
        } else {
            $res = array('status' => -1, 'msg' => '验证码发送失败,请联系管理员');
        }
        return $res;
    }

    /**
     * 短信验证码验证
     * @param $mobile   手机
     * @param $code  验证码
     * @return bool
     */
    public function checkSmsCode($mobile, $code) {
        //判断是否存在验证码
        $data = M('sms')->where(array('mobile' => $mobile, 'code' => $code))->order('id desc')->find();
        if (empty($data))
            return array('status' => -1, 'msg' => '手机验证码不匹配');
        //获取时间配置
        $sms_time_out = xrkCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //验证是否过时
        if ((time() - $data['add_time']) > $sms_time_out)
            return array('status' => -1, 'msg' => '手机验证码超时'); //超时处理
        //M('sms')->where(array('mobile' => $mobile, 'code' => $code))->delete();
        return array('status' => 1, 'msg' => '验证成功');
    }

    /**
     * 发送验证码
     * @param $sender 接收人
     * @param $type 发送类型
     * @return json
     */
    public function sendValidateCode($sender, $type) {
        $sms_time_out = xrkCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 180;
        //获取上一次的发送时间
        $send = session('validate_code');
        if (!empty($send) && $send['time'] > time() && $send['sender'] == $sender) {
            //在有效期范围内 相同号码不再发送
            $res = array('status' => -1, 'msg' => '规定时间内,不要重复发送验证码');
        }
        $code = mt_rand(1000, 9999);
        if ($type == 'email') {
            //检查是否邮箱格式
            if (!check_email($sender))
                $res = array('status' => -1, 'msg' => '邮箱码格式有误');
            $send = send_email($sender, '验证码', '您好，你的验证码是：' . $code);
        }else {
            if (!check_mobile($sender))
                $res = array('status' => -1, 'msg' => '手机号码格式有误');
            //$send = sendSMS($sender,'您好，你的验证码是：'.$code);
            $send = sendSMS($sender, $code);
        }
        if ($send) {
            $info['code'] = $code;
            $info['mobile'] = $sender;
            $info['add_time'] = time();
            $info['session_id'] = session_id();
            $check['is_check'] = 0;
            $info['time'] = time() + $sms_time_out; //有效验证时间
            M('sms')->add($info);
            session('validate_code', $info);
            $res = array('status' => 1, 'msg' => '验证码已发送，请注意查收');
        } else {
            $res = array('status' => -1, 'msg' => '验证码发送失败,请联系管理员');
        }
        return $res;
    }

    public function checkValidateCode($code, $sender) {
        $check = session('validate_code');
        if (empty($check)) {
            $res = array('status' => 0, 'msg' => '请先获取验证码');
        } elseif ($check['time'] < time()) {
            $res = array('status' => 0, 'msg' => '验证码已超时失效');
        } elseif ($code != $check['code'] || $check['mobile'] != $sender) {
            $res = array('status' => 0, 'msg' => '验证失败,验证码有误');
        } else {
            $check['is_check'] = 1; //标示验证通过
            session('validate_code', $check);
            $res = array('status' => 1, 'msg' => '验证成功');
        }
        return $res;
    }

    public function showUserId($user_id = 0) {
        if ($user_id)
            return $user_id;
        return session('?user') ? session('user')['user_id'] : 0;
    }

}
